#ifndef AABBTREE_H_
#define AABBTREE_H_

#include "shapes.h"
#include "Geometry.h"

namespace physicsworks {

/**
 * Represents the nodes with its left and right child.
 */
struct AABBTreeNode {
	AABox box;
	AABBTreeNode* leftChild;
	AABBTreeNode* rightChild;
	
	~AABBTreeNode() {
		if (leftChild) delete leftChild;
		if (rightChild) delete rightChild;
	}
};

/**
 * Represents a leaf node with its corresponding face.
 */
struct AABBTreeLeaf : public AABBTreeNode {
	FaceRef* face;
};

// Face representation suited for the AABBTree construction
struct FaceCache {
	FaceRef* face;
	vec3 centroid;
};

class AABBTree {
public:
	AABBTree(vec3* vertices, int numVertices, const int* verticesIndices, int numFaces);
	~AABBTree();
	AABox getBoundingBox() const { return root->box; }

private:
	Geometry geometry;
	AABBTreeNode* root;

private:
	void topDownConstruction(AABBTreeNode** tree, FaceCache* faces, int numFaces) const;
	int computePartition(FaceCache* faces, int numFaces, const AABox& bv) const;
	AABox computeBoundingVolume(FaceCache* faces, int numFaces) const;
};

}

#endif /*AABBTREE_H_*/
